package stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class PolandNotation {

    public static void main(String[] args) {
        // 先顶一个逆波兰表达式
        String exp = "3 4 + 5 x 6 - ";
        //先将表达式放入ArrayList
        //将ArrayList传递给方法，配合栈完成计算
        //将逆波兰表达式以此将数据和运算法放入ArrayList中
        List<String> list = getListString(exp);
        System.out.println(list);
        System.out.println(calculator(list));

    }
    //将中缀表达式转换为List
    public static List<String> toInfixExpressionList(String str){
        ArrayList<String> list = new ArrayList<String>();
        int index = 0;//指针，用于遍历
        String s ;//对多位数拼接
        char c;
        do {
            //如果C是一个非数字，就需要加入到ls
            if (((c = str.charAt(index)) < 48) || ((c = str.charAt(index)) > 57)){
                list.add(""+c);
                index++;
            }else {
                s = "";//先将str初始化
                while (index < str.length() && (c = str.charAt(index)) >= 48 && ((c = str.charAt(index)) > 57)){
                    str += c;
                    index++;
                }
            }
        }while (index < str.length() );
        return list;
    }

    public static List<String> getListString(String s){
        String[] s1 = s.split(" ");
        ArrayList<String> list = new ArrayList<String>();
        for (String str:s1){
            list.add(str);
        }
        return list;
    }

    public static int calculator(List<String> list){
        Stack<String> stack = new Stack<String>();

        for (String s:list){
            if (s.matches("\\d+")){
                stack.push(s);
            }else {
                int num1 = Integer.parseInt(stack.pop());
                int num2 = Integer.parseInt(stack.pop());
                int res = 0;
                if (s.equals("+")){
                    res = num1 + num2;
                }else if (s.equals("-")){
                    res = num1 - num2;
                }else if (s.equals("*")||s.equals("x")){
                    res = num1 * num2;
                }else if (s.equals("/")){
                    res = num1 / num2;
                }else {
                    throw new RuntimeException("运算符有误");
                }
                stack.push(String.valueOf(res));
            }
        }return Integer.parseInt(stack.pop());
    }
}
